package com.lzc.tlmail.tlmailproduct.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lzc.common.utils.R;
import com.lzc.tlmail.tlmailproduct.entity.SkuImagesEntity;
import com.lzc.tlmail.tlmailproduct.entity.SpuInfoDescEntity;
import com.lzc.tlmail.tlmailproduct.feign.SeckillFeignService;
import com.lzc.tlmail.tlmailproduct.service.*;
import com.lzc.tlmail.tlmailproduct.vo.SeckillSkuInfovo;
import com.lzc.tlmail.tlmailproduct.vo.SkuItemVo;
import com.lzc.tlmail.tlmailproduct.vo.SkuSaleAttrVo;
import com.lzc.tlmail.tlmailproduct.vo.SpuBaseGroupAttrVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzc.common.utils.PageUtils;
import com.lzc.common.utils.Query;

import com.lzc.tlmail.tlmailproduct.dao.SkuInfoDao;
import com.lzc.tlmail.tlmailproduct.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SeckillFeignService seckillFeignService;
    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    //注入线程池
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 检索sku
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and(w->{
                w.eq("sku_id",key).or().eq("sku_name",key);
            });
        }
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }
        String min = (String) params.get("min");
        if(!StringUtils.isEmpty(min)){

            queryWrapper.ge("price",min);
        }
        String max = (String) params.get("max");
        if(!StringUtils.isEmpty(max)){

            BigDecimal bigDecimal = new BigDecimal(max);
            if(bigDecimal.compareTo(new BigDecimal("0"))==1){
                queryWrapper.le("price",bigDecimal);
            }

        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 根据spuid查出所有sku信息
     * @param spuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> querySkuBySpuId(Long spuId) {
        List<SkuInfoEntity> skuInfoEntities = this.list(new LambdaQueryWrapper<SkuInfoEntity>().eq(SkuInfoEntity::getSpuId,spuId));
        return skuInfoEntities;
    }

    /**
     *根据skuId得到sku信息展示详情页
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVo item(Long skuId) {
        SkuItemVo skuItemVo = new SkuItemVo();
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            //1sku基本信息
            SkuInfoEntity skuInfoEntity = this.getBaseMapper().selectById(skuId);
            skuItemVo.setSkuInfoEntity(skuInfoEntity);
            return skuInfoEntity;
        }, threadPoolExecutor);
        CompletableFuture<Void> skuSaleAttrFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            //3spu销售属性
            List<SkuSaleAttrVo> skuSaleAttrVos = skuSaleAttrValueService.getSkuSaleAttrBySpuId(res.getSpuId());
            skuItemVo.setSpuSaleAttrs(skuSaleAttrVos);
        }, threadPoolExecutor);

        CompletableFuture<Void> descFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            //4spu详细信息
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setSpuInfoDescEntity(spuInfoDescEntity);
        }, threadPoolExecutor);

        CompletableFuture<Void> baseAttrFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            //5spu规格参数  根据spuId和分类id获得spu基本属性
            List<SpuBaseGroupAttrVo> spuBaseGroupAttrVos = attrGroupService.getAttrGroupAndAttrBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setSpuBaseGroupAttrVos(spuBaseGroupAttrVos);
        }, threadPoolExecutor);


        //2sku图片信息
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> skuImagesEntities = skuImagesService.list(new LambdaQueryWrapper<SkuImagesEntity>()
                    .eq(SkuImagesEntity::getSkuId, skuId));
            skuItemVo.setSkuImagesEntitys(skuImagesEntities);
        }, threadPoolExecutor);


        //秒杀的信息
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R seckillSkuInfo = seckillFeignService.getSeckillSkuInfo(skuId);
            if(seckillSkuInfo.getCode()==0){
                SeckillSkuInfovo seckillSkuInfoData = seckillSkuInfo.getData("data", new TypeReference<SeckillSkuInfovo>() {
                });
                skuItemVo.setSeckillSkuInfovo(seckillSkuInfoData);
            }
        }, threadPoolExecutor);


        //等到所有任务都完成 相当于是等上面所有都完成了再返回数据 不然可能会拿不到数据 应为这相当于多线程了
        try {
            CompletableFuture.allOf(skuSaleAttrFuture,descFuture,baseAttrFuture,imageFuture,seckillFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return skuItemVo;
    }

}